<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <div class="login-logo" />
        <h3 class="title">园区能源与碳排放管理平台</h3>
      </div>

      <el-form-item
        v-show="!isMainAccount"
        :prop="'mainUserName'"
        :rules="{
          required: !isMainAccount,
          trigger: 'blur',
          message: '主账号不能为空，请重新输入'
        }"
        class="userName-item"
      >
        <el-input
          ref="mainUserName"
          v-model.trim="loginForm.mainUserName"
          placeholder="请输入主账号"
          name="mainUserName"
          type="text"
          tabindex="1"
          auto-complete="on"
        >
          <div :slot="'prefix'" class="account-icon">
            <img src="~@/assets/images/account.png" />
          </div>
        </el-input>
      </el-form-item>

      <el-form-item prop="userName" class="userName-item">
        <el-input
          ref="userName"
          v-model="loginForm.userName"
          placeholder="请输入用户名"
          name="userName"
          type="text"
          tabindex="1"
          auto-complete="on"
        >
          <i :slot="'prefix'" :class="'el-input__icon el-icon-user user'" />
        </el-input>
      </el-form-item>

      <el-form-item prop="password" class="password-item">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        >
          <i :slot="'prefix'" :class="'el-input__icon el-icon-lock password'" />
        </el-input>
        <span class="show-pwd" @click="showPwd" />
      </el-form-item>

      <div class="assist-box">
        <el-checkbox v-model="checked">记住密码</el-checkbox>
<!--        <span class="third-login">第三方登录</span>-->
        <span class="forget-password" @click="clickForgetPassword"
          >忘记密码?</span>
      </div>

      <el-button
        class="login-primary"
        :loading="loading"
        type="primary"
        style="width: 100%"
        :disabled="isDisabled"
        @click.native.prevent="handleLogin"
      >
        登录
      </el-button>
      <div v-if="showTenantCode" class="checkout-type flex flex-jcc">
        <span
          class="type-item flex flex-aic"
          style="cursor: pointer"
          @click="checkoutType"
        >
          {{ loginTypeName }}登录
          <i class="el-icon-arrow-right" style="font-size: 12px" />
        </span>
      </div>
    </el-form>
  </div>
</template>

<script>
import { Base64 } from 'js-base64'
import { encryptByMd5 } from '@/utils/index'
import { setToken, setCustomToken } from '@/utils/auth'
export default {
  name: 'Login',
  data() {
    return {
      checked: false,
      loginForm: {
        userName: '',
        password: '',
        mainUserName: ''
      },
      loginRules: {
        mainUserName: [
          {
            required: true,
            trigger: 'blur',
            message: '主账号不能为空，请重新输入'
          }
        ],
        userName: [
          {
            required: true,
            trigger: 'blur',
            message: '用户名不能为空，请重新输入'
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '密码不能为空，请重新输入'
          }
        ]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      showTenantCode: false,
      isMainAccount: true
    }
  },
  computed: {
    isDisabled() {
      const { userName, password } = this.loginForm
      return !userName || !password
    },
    loginTypeName() {
      return this.isMainAccount ? '子账号' : '主账号'
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },

  async created() {
    this.enableTenant()

    //本地开发注释即可，打包发布的时候打开这段代码，用于实现单点登录跳转逻辑
    // if (!this.$route.query.code) {
    //   window.location.href = `http://192.168.1.117/agcloud-sso/oauth/authorize?client_id=${'nengtan-clientId'}&response_type=code&redirect_uri=${'http://81.69.253.26:8189/login'}`
    // } else {
      //回调拿到code后去调接口获取登录信息
      // let { data } = await this.$api.newLogin.newLoginToken(
      //   this.$route.query.code
      // )
      // let { data } = {
      //   code: '1000',
      //   success: true,
      //   data: {
      //     tenantId: '000',
      //     userName: 'admin',
      //     fullName: 'admin',
      //     loginTm: '2024-08-22 16:23:47',
      //     token:
      //       'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqd3QiLCJhdWQiOiJ3ZWIiLCJpc3MiOiJpdGl0X2dyYXNzIiwiZXhwIjoxNzI0MzU4MjI1LCJpYXQiOjE3MjQzMTUwMjYsImdyYXNzSnd0IjoiMDAwIiwianRpIjoiN2Y1YzUzMjMxYjc3NGJlMmExNTMyNWZiMjUxMDgzMDQifQ.hl0_xZE8_aPN7q-NWUmpQrGrLM9pTmv1hLeXN3szh8E',
      //     avatarUrl:
      //       'http://minio.itit.cloud/customs-platform-dev/a713ad6271124601b86e899d3ec53018.png'
      //   }
      // }
      // const Base64Password = Base64.encode(this.loginForm.password) // base64加密
      // setToken(data.token)
      // setCustomToken('grassJwt',data.token)
      // this.setLocalStorageUser(this.loginForm.mainUserName, data.userName, 'xxxx', 7)
      // this.$router.push({ path: this.redirect || '/' })
    // }
  },
  mounted() {
    this.getLocalStorageUser()
  },
  methods: {
    /**
     * 是否开启租户
     */
    enableTenant() {
      this.$api.enableTenant({}).then((res) => {
        if (Number(res.code) === 1000) {
          this.showTenantCode = res.data
        } else if (res.msg) {
          this.$message({ type: 'error', message: res.msg })
        }
      })
    },
    // 显示密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (this.isMainAccount) {
            this.loginForm.mainUserName = ''
          }
          /* ------ 账号密码的存储 ------ */
          const Base64Password = Base64.encode(this.loginForm.password) // base64加密
          const password = encryptByMd5(this.loginForm.password) // Md5加密
          if (this.checked) {
            this.setLocalStorageUser(
              this.loginForm.mainUserName,
              this.loginForm.userName,
              Base64Password,
              7
            )
          } else {
            localStorage.removeItem('client-serve-acc')
          }
          this.loading = true
          this.$store
            .dispatch('user/login', {
              ...this.loginForm,
              password
            })
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch((error) => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clickForgetPassword() {
      this.$message({ message: '请联系管理员重置密码！' })
    },
    // 设置localStorage
    setLocalStorageUser(mainUserName, userName, password, days) {
      localStorage.setItem(
        'client-serve-acc',
        JSON.stringify({
          mainUserName,
          userName,
          password,
          days,
          time: new Date().getTime()
        })
      )
    },
    // 读取localStorage 将用户名和密码回显到input框中
    getLocalStorageUser() {
      const accMsg = JSON.parse(localStorage.getItem('client-serve-acc'))
      if (!accMsg) {
        return
      }
      const { mainUserName, userName, password, days, time } = accMsg
      const date = new Date().setTime(Number(time) + 24 * 60 * 60 * 1000 * days)
      // 判断是否过期
      if (new Date().getTime() > date) {
        localStorage.removeItem('client-serve-acc')
        return
      }
      this.loginForm.mainUserName = mainUserName
      this.loginForm.userName = userName
      this.loginForm.password = Base64.decode(password) // base64解密
      this.checked = true
    },
    // 切换登录类型
    checkoutType() {
      this.isMainAccount = !this.isMainAccount
      if (this.isMainAccount) {
        this.loginForm.mainUserName = ''
      }
    }
  }
}
</script>

<style lang="scss">
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 100%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      color: #333;
      height: 47px;
      padding-left: 40px;
    }
  }

  .el-input__prefix {
    .user,
    .password {
      color: #333;
      font-size: 20px;
    }
  }

  .el-form-item {
    border: 1px solid #ececec;
    border-radius: 5px;
    color: #333;
  }
}
</style>

<style lang="scss" scoped>
.login-container {
  position: relative;
  min-height: 100%;
  width: 100%;
  height: 100%;
  background-image: url(~@/assets/images/login-bg.png);
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;

  .login-form {
    position: absolute;
    right: 120px;
    top: 50%;
    transform: translateY(-50%);
    width: 450px;
    max-width: 100%;
    padding: 48px 40px 40px 40px;
    overflow: hidden;
    background-color: #fff;
  }

  .title-container {
    position: relative;
    height: 50px;
    line-height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 70px;

    .login-logo {
      display: flex;
      width: 46px;
      height: 48px;
      background-image: url(~@/assets/images/logo.png);
      background-repeat: no-repeat;
      background-size: cover;
      overflow: hidden;
      margin-right: 20px;
    }

    .title {
      font-size: 25px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #303133;
      line-height: 48px;
    }
  }

  .assist-box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 100px;
    color: #333;
    font-size: 14px;

    .third-login {
      color: rgb(219,139,57);
      justify-content: right;
      cursor: pointer;
    }
    .forget-password {
      color: rgb(219,139,57);
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #666;
    cursor: pointer;
    user-select: none;
  }

  .login-primary {
    height: 50px;
    &.is-disabled {
      background-color: rgba(219,139,57, 0.4);
      color: #fff;
      border-color: rgba(219,139,57, 0.4);
    }
  }
}

.account-icon {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    height: 20px;
    width: 20px;
    margin-left: 5px;
  }
}

.checkout-type {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  color: #303133;
  line-height: 20px;
  width: 100%;
  text-align: center;
  margin-top: 22px;
  width: 100%;
}
</style>
